﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace SW.EF.DAL
{
    public class UnitOfWork : IUnitOfWork
    {
        private EFPermissionDBEntities _context;

        #region 权限模块仓储 字段

        private IRepository<Role,int> _roleRepository;
        private IRepository<User, int> _userRepository;
        private IRepository<Permission, int> _permissionRepository;
        private IRepository<UserPermissionRelation, int> _userPermissionRelationRepository;

        #endregion

        public UnitOfWork()
        {
            this._context = DbContextHelper.GetDbContext<EFPermissionDBEntities>();
        }

        #region 权限模块仓储 属性

        public IRepository<Role,int> RoleRepository
        {
            get
            {
                if (_roleRepository != null) return _roleRepository;
                _roleRepository = new Repository<Role, int>(_context);
                return _roleRepository;
            }
        }

        public IRepository<User, int> UserRepository
        {
            get
            {
                if (_userRepository != null) return _userRepository;
                _userRepository = new Repository<User, int>(_context);
                return _userRepository;
            }
        }

        public IRepository<Permission, int> PermissionRepository
        {
            get
            {
                if (_permissionRepository != null) return _permissionRepository;
                _permissionRepository = new Repository<Permission, int>(_context);
                return _permissionRepository;
            }
        }

        public IRepository<UserPermissionRelation, int> UserPermissionRelationRepository
        {
            get
            {
                if (_userPermissionRelationRepository != null) return _userPermissionRelationRepository;
                _userPermissionRelationRepository = new Repository<UserPermissionRelation, int>(_context);
                return _userPermissionRelationRepository;
            }
        }

        #endregion

        #region 方法

        public int SaveChanges()
        {
            return this._context.SaveChanges();
        }

        public void Dispose()
        {
            if (_context != null) _context.Dispose();
        }

        #endregion

        public EFPermissionDBEntities DbContextFacotry { get; set; }
    }
}
